﻿@model IEnumerable<Qu.SeniorProject.Model.ProjectSummary>
           
@section head {
    <style>
        em { font-weight: bold; padding-right: 1em; vertical-align: top; color: red; }        
    </style>

@*    <script type="text/javascript">
       function deleteConfirmation(response, status, data) {
           // display a status message with highlight
           $('#MarkProjectAsCompleteDiv').text(response.message);
           $('#MarkProjectAsCompleteDiv').effect("highlight", {}, 3000);

        }
    </script>*@

   <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $('#message_bar').displayMessage({
                    message: '@TempData["Message"]',
                    color: 'white',
                    speed: 'fast',
                    autohide: true
                })
            });

            $(function () {
                $("#PeriodIDdropdown").live("change keyup", function () {
                    this.form.submit();
                })
            });

              // AJAX activity indicator bound to ajax start/stop document events
              $(document).ajaxStart(function () {
                $('#ajaxBusy').show();
              }).ajaxStop(function () {
                $('#ajaxBusy').hide();
              });

            // Bind a click handler to the "Login" link
//            $(function () {
//                $("#ReleaseGrades").click(function (e) {
            function showReleaseGradeForm(projectId) {
                // Display the login dialog
                $("#dialog").dialog({
                    minWidth: 400,
                    modal: true,
                    resizable: false,
                    show: "scale",
                    hide: "scale",
                    buttons: {
                        Ok: function () {
                            var addressFeedbackRating = $("#addressFeedbackRating").val();
                            var addressFeedbackComment = $("#addressFeedbackComment").val();

                            if (addressFeedbackRating == "") {
                                alert("Select a rating first");
                            }
                            else {
                                var controllerUrl = "@Url.Action("ReleaseGrades", "Home")";
                                var params = {
                                    projectId: projectId, 
                                    ratingId: addressFeedbackRating,
                                    comments: addressFeedbackComment
                                };

                                $('#ReleaseGradesDiv').hide();

                                $.ajax({
                                  type: 'POST',
                                  dataType: 'json',
                                  url: controllerUrl,
                                  data: params,
                                  success: 
                                       function (data) {
                                          if (data.success)
                                          {
                                               //alert("Data Loaded: " + data.message);
                                               $('#ReleaseGradesDiv').show();
                                               $('#ReleaseGradesDiv' + projectId).text(data.message);
                                               $('#ReleaseGradesDiv' + projectId).effect("highlight", {}, 3000);
                                            }
                                           else
                                           {
                                                alert(data.message);
                                           }
                                       },
                                  error : function(data) { 
                                    alert("Operation failed because : " + data + "\ns Please try again."); 
                                    $('#ReleaseGradesDiv').show();
                                    }
                                });

                                $(this).dialog("close");

//                                $.post(controllerUrl, params,
//                                   function (data) {
//                                       //alert("Data Loaded: " + data.message);
//                                       // Make Ajax Call - response.message
//                                       $('#ReleaseGradesDiv' + projectId).text(data.message);
//                                       $('#ReleaseGradesDiv' + projectId).effect("highlight", {}, 3000);
//                                   });

                            }
                        },
                        Cancel: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }
//                e.preventDefault();
//            })
        //});
     </script>

   <script type="text/javascript" language="javascript">

       function ValidateFileType(requiredExtension, fileInputControl, uploadButton, uploadForm) {

           //get filepath from fileupload control on the page
           var fileUpload = $(fileInputControl).val();

           //extracting part of the filename from dot
           var extension = fileUpload.substring(fileUpload.lastIndexOf('.'));

//           //valid file type - static
//           var ValidFileType = ".jpg , .png , .bmp";
//           //or fetch it from config file for flexibility ,
//           //we can save valid file type list in web.config also & fetch it during validation process
//           var ValidFileTypeConfig = '<%=ConfigurationManager.AppSettings["ValidFileType"].ToString() %>';

           //check whether user has selected file or not
           if (fileUpload.length > 0) {

               //check file is of valid type or not
               if (requiredExtension.toLowerCase().indexOf(extension) < 0) {
                   alert("Invalid file type, you must select a " + requiredExtension + " file.");
               }
               else {
                   //alert("file type is valid...");
                   //$(uploadButton).attr('value', 'Please wait while the file is being uploaded...');
                   var btn = $(uploadButton);
                   var disBtn = $("<input type='button' value='Please wait while the file is being uploaded...'/>").attr("disabled", "disabled");

                   btn.hide().after(disBtn);
                   var form = $(uploadForm);
                   form.submit();

//                   $(uploadButton).unbind('click');
//                   $(uploadButton).attr("disabled", true);
                   return true;
               }
           }
           else {
               alert("Please select file for upload...");
           }
           return false;
       }
   </script>
 }


@{
    ViewBag.Title = "CSE Senior Projects";
}

@if (ViewBag.StudentID == null)
{
    <!-- Login dialog -->
    <div id="dialog" title="Assess Addressing Examiners Feedback" style="display: none">
        <table cellpadding="4">
            <tr>
                <td><em>*</em>Rating:</td>
                <td>
                @{
    var requiredField = new Dictionary<string, object>();
    requiredField.Add("class", "required");
    requiredField.Add("id", "addressFeedbackRating");

    SelectList ratingList = new SelectList(ViewBag.Ratings, "RatingID", "Description");
                    @Html.DropDownList("addressFeedbackRating", ratingList, "", requiredField);
                 }
                </td>
            </tr>
            <tr>
                <td>Comments:</td>
                <td>
                @{
                                                                                              var commentsHtmlAttributes = new Dictionary<string, object>();
                                                                                              commentsHtmlAttributes.Add("id", "addressFeedbackComment");
                                                                                              commentsHtmlAttributes.Add("width", "100%");
                       @Html.TextArea("addressFeedbackComment", commentsHtmlAttributes);
                 }
                </td>
            </tr>
            <tr>
              <td colspan="2">
                Are you sure you would like to release the grades to students? 
                <br />Please make sure that all the expected deliverables were submitted to you (note that often once the students access their grades they 'disappear').
               </td>
            </tr>
        </table>
    </div>
}

@if (ViewBag.StudentID == null)
{
    using (Html.BeginForm())
    {
        <b>Academic Year:</b> @Html.AjaxDropdown("PeriodID", controller: "ProjectPeriodAjaxDropdown") 
        <br /><br />
    }
}

@if (!string.IsNullOrEmpty(ViewBag.Message))
{
    <h3>@ViewBag.Message</h3>
    
    if (ViewBag.StudentID == null)
    {
        if ((bool)ViewBag.CanAddProject)
        {
                @Html.ActionLink("Add Project", "AddProject", "Home");
        }
    }
    else
    {
       @Html.Partial("_MessageToStudentWithoutProject");
    }
    return;
}

<div id='GradeDetails'></div>
<table>
    <tr>
        <th>
            ID
        </th>  
        <th>
            Year
        </th>
        @if (ViewBag.StudentID == null)
        {
            <th>
                Your Role
            </th>      
        }
        else
        {
            <th width="0px"></th>  
        }
        <th>
            Title
        </th>
        <th>
            Students
        </th>
        <th>
            Supervisor
        </th>
        <th width="140px"></th>
    </tr>

    @DisplayProjectDetails()
</table>

@if (ViewBag.StudentID == null && (bool)ViewBag.CanAddProject)
{
    <p>
        @Html.ActionLink("Add Project", "AddProject", "Home")
    </p>
}


@helper GetActionLinks(string role, int projectId, int periodId)
    {
        var actionLinks = Qu.SeniorProject.Model.ProjectRepository.GetActionLinks(role, projectId, periodId);
        var routeValues = new System.Web.Routing.RouteValueDictionary();
        foreach (var actionLink in actionLinks)
        {

            if (actionLink.ActionName == "ReleaseGrades")
                {
                    <div id="ajaxBusy" style="display: none"><img src="@Url.Content("~/Content/Images/ajaxloading.gif")" /><p id="ajaxBusyMsg">Please wait...</p></div>
                    <div id='@Html.Raw("ReleaseGradesDiv" + @projectId.ToString())'><a href="#" id="ReleaseGrades" onclick="showReleaseGradeForm('@projectId')">Release Grades to Students</a></div>
@*                    <div id="MarkProjectAsCompleteDiv">
                    @Ajax.ActionLink("Release Grades to Students", "MarkProjectAsComplete", new { projectID = item.ProjectID },
                                new AjaxOptions
                                {
                                    UpdateTargetId = "message_bar",
                                    HttpMethod = "POST",
                                    Confirm = "Are you sure you would like to release the grades to students? Please make sure that all the expected deliverables was submitted to you (note that often once the students access their grades they 'disappear').",
                                    OnSuccess = "deleteConfirmation"
                                })
                    </div>*@
               }
               else
               {
                    routeValues.Clear();

                    foreach (var parameter in actionLink.Parameters.Split(','))
                    {
                        string[] parts = parameter.Split('=');
                        routeValues.Add(parts[0], parts[1]);
                    }

                   //routeValues = 
                   @Html.ActionLink(actionLink.LinkLabel, actionLink.ActionName, actionLink.ControllerName, routeValues, null)
               }
               <br /><br />
        }
}


@helper DisplayProjectDetails()
    {
        foreach (var item in Model)
        {
    <tr>
        <td>
           <b> @Html.ActionLink(item.ProjectID.ToString(), "ProjectDetails", new { id = item.ProjectID }) </b>
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ProjectYear)
        </td>
        @if (ViewBag.StudentID == null)
        {
            <td>
                @Html.DisplayFor(modelItem => item.Role)
            </td>
        }
        else
        {
            <td></td>
        }
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            @Html.Raw(item.Students)
        </td>
        <td>
            @Html.Raw(item.Supervisors)
        </td>

        <td rowspan='3'>
           @GetActionLinks(item.Role, item.ProjectID, item.PeriodId)

        </td>
    </tr>
    
    <tr>
        <td colspan='6'>
             <b>Abstract: </b>@Html.Raw(item.Abstract)
             <br />
        </td>
    </tr>
        if (item.PresentationDateTime != null && !string.IsNullOrEmpty(item.PresentationRoom)
                    && item.PresentationDateTime >= DateTime.Now.AddDays(-1)
                    && item.PresentationDateTime.Value.AddDays(-6) <= DateTime.Now)
        {
           <tr>
                    <td colspan='4'>
                         <b>Presentation Time:</b> @item.PresentationDateTime.Value.ToString("dd/MM/yyyy hh:mm tt") <b> at </b> @item.PresentationRoom
                         <br />

                         @if (item.PosterTime != null)
                         {
                            <b>Poster and Demo Time:</b> @item.PosterTime <b> at </b> @item.PosterVenue
                         }
                    </td>
               
                @if (!string.IsNullOrEmpty(item.Examiners))
                {
                    <td  colspan='2'>
                        <b>Examiners: </b>@Html.Raw(item.Examiners)
                    </td>
                }
                else
                    if (!string.IsNullOrEmpty(item.ProposalExaminer))
                    {
                    <td  colspan='2'>
                        <b>Examiner: </b>@Html.Raw(item.ProposalExaminer)
                    </td>
                    } 
          </tr>
        }
  
    <tr>
        <td colspan='6'>
             @foreach (var doc in item.Documents)
             {
                 @Html.ActionLink(linkText: doc.DocumentName, actionName: "Index", controllerName: "document", routeValues: new { id = string.Format("pd{0}", doc.DocumentId) }, htmlAttributes: null);
                 <br />
             }
             <br />
        </td>
    </tr>
             if (ViewBag.StudentID != null || (string)ViewBag.UserName == "erradi")
             {
                  @GetDocumentUploadForms(item.ProjectID.ToString())

                  @* Enter in the config table: revised interim report, FinalReport,  FinalPresentation, Poster, RevisedFinalReport *@
             }
        } 
}


@helper GetDocumentUploadForms(string projectId)
    {
    
        var deliverables = Qu.SeniorProject.Model.DocumentRepository.GetDeliverableDates(int.Parse(projectId));

        if (deliverables == null)
        {
            return;
        }

        foreach (var deliverable in deliverables)
        {
            string documentType = deliverable.DocumentType; //"InterimReport";
            string documentDescription = deliverable.DocumentDescription; //"Interim Report";
            string documentExtension = deliverable.DocumentExtension; //".docx";
            string dueDate = string.Format("Due by {0: hh:mm tt} on {1: dddd dd MMMM yyyy}", deliverable.DueDate, deliverable.DueDate);
            int academicYear = deliverable.AcademicYear;

            string fileInputName, uploadButtonName, uploadFormName;
            fileInputName = string.Format("{0}FileInput{1}", documentType, projectId);
            uploadButtonName = string.Format("{0}UploadButton{1}", documentType, projectId);
            uploadFormName = string.Format("{0}UploadForm{1}", documentType, projectId);

        <tr class="uploadRow"><td colspan='7'>
            <div><b>Upload @documentDescription</b> (must be @documentExtension file) <span style="color : Red;"> - @dueDate </span></div><br />
            <div style="color : Maroon;">Browse and select the file to be uploaded then click the Upload button</div><br />
            @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = uploadFormName }))
            {
                @Html.Hidden("ProjectId", projectId)
                @Html.Hidden("DocumentType", documentType)
                @Html.Hidden("DocumentExtension", documentExtension)
                @Html.Hidden("AcademicYear", academicYear)
                <text>File: </text><input type="file" name="file" id='@fileInputName' size="100" />
                <input type="submit" value="Upload" id='@uploadButtonName'
                    onclick="return ValidateFileType('@documentExtension',  '#@fileInputName' , '#@uploadButtonName' , '#@uploadFormName');"/>
            }
            <br />
        </td></tr>
        }
    
}